const {trim} = require('validator')
const crypto = require('crypto')
const Conf = require('../config/config')
const {HttpError} = require('./error')
let Tools = {}

/**
 * 去除对象值前后空格
 */
Tools.trimObjectValue = obj => {
  let _temp = {}
  for (let item in obj) {
    _temp[item] = trim(obj[item])
  }
  return _temp
}
/**
 * 友好时间
 */
Tools.timAgo = (time) => {
  if (!time instanceof Date) {
    time = new Date(time)
  }
  let interval = Math.floor((Date.now() -time ) / 1000) 
  let temp = 0
  if(interval < 60) {
    return interval +' 秒前';
  }
  if((temp = interval / 60 ) < 60){
    return Math.floor(temp) + ' 分钟前';
  }
  if((temp = temp / 60 ) < 24){
    return Math.floor(temp) + ' 小时前';
  }
  if((temp = temp / 24 ) < 30){
    return Math.floor(temp) + ' 天前';
  }
  if((temp = temp / 30 ) < 12){
    return Math.floor(temp) + ' 月前';
  }
  return Math.floor(temp / 12) + ' 年前';
}

/**
 * 加密
 */
Tools.encrypted = (str) => {
  const cipher = crypto.createCipher('aes192', Conf.cipherKey)
  let encrypted = cipher.update(str, 'utf8', 'hex' )
  encrypted += cipher.final('hex')
  return encrypted
}

/**
 * 解密
 */
Tools.decrypted = (encrypted) => {
  const decipher = crypto.createDecipher( 'aes192', Conf.cipherKey )
  try {
    let decrypted = decipher.update( encrypted, 'hex', 'utf8' )
    decrypted += decipher.final( 'utf8' )
    return decrypted
  } catch (err) {
    // 修改错误信息  默认 TypeError: Bad input string
    throw new Error('Token 解析失败 可能被篡改！')
  }
  
}


/**
 * 生成随机字符串
 */
Tools.randomString = len=> {
  len = len || 5
  const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
  const maxPos = chars.length
  let pwd = ''
  for ( let i = 0; i < len; i++ ) {
    pwd += chars.charAt( Math.floor( Math.random() * maxPos ) )
  }
  return pwd
}

module.exports = Tools